package com.ruoyi.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class ESConfig {

    @Value("${menu.elasticsearch.host}")
    private String host;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        //1.连接rest接口
        String[] host_port_array = host.split(",");
        List<HttpHost> httpHostList  = new ArrayList<>();

        Arrays.stream(host_port_array).forEach(host_port->{
            String[] split = host_port.split(":");
            HttpHost http=new HttpHost(split[0], Integer.parseInt(split[1]),"http");
            httpHostList.add(http);
        });

        RestClientBuilder builder= RestClient.builder(httpHostList.toArray(new HttpHost[0]));//rest构建器
        RestHighLevelClient restHighLevelClient=new
                RestHighLevelClient(builder);//高级客户端对象

        return restHighLevelClient;
    }
}
